package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.IOUtils;
import com.sky.properties.BaiduGeoProperties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URI;
import java.util.Map;

@Component
public class BaiduGeoUtil {

    @Autowired
    private BaiduGeoProperties properties;

    public Integer getDistance(String remoteAddr){
        //获取商家经纬度
        JSONObject restaurantMap = getLatLng(properties.getRestaurantAddr());

        //获取用户经纬度
        JSONObject remoteMap = getLatLng(remoteAddr);

        //获取两点骑行距离
        Integer distance = getDistance(restaurantMap, remoteMap);

        return distance;
    }
    private JSONObject getLatLng(String address) {
        try {
            //构造客户端
            CloseableHttpClient client = HttpClients.createDefault();
            //构造请求
            HttpGet get = new HttpGet();
            URI uri = new URI(properties.getGetAddrUrl() + "address=" + address + "&output=json" + "&ak=" + properties.getAk() + "&callback=showLocation");
            get.setURI(uri);
            //发送请求
            CloseableHttpResponse response = client.execute(get);
            //判断是否获取成功
            if (response.getStatusLine().getStatusCode() != 200) throw new RuntimeException("获取地址经纬度失败");
            //解析结果
            String entity = EntityUtils.toString(response.getEntity());
            String jsonString = entity.substring(entity.indexOf("(") + 1, entity.indexOf(")"));
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONObject result = (JSONObject)jsonObject.get("result");
            JSONObject location = (JSONObject)result.get("location");


            client.close();
            response.close();

            return location;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取地址经纬度失败");
        }
    }

    private Integer getDistance(Map origin, Map remote) {
        String originLng =  origin.get("lng").toString();
        String orLng = originLng.substring(0, originLng.indexOf(".") + 7);
        String originLat = origin.get("lat").toString();
        String orLat = originLat.substring(0, originLat.indexOf(".") + 7);

        String remoteLng = remote.get("lng").toString();
        String reLng = remoteLng.substring(0, remoteLng.indexOf(".") + 7);
        String remoteLat = remote.get("lat").toString();
        String reLat = remoteLat.substring(0, remoteLat.indexOf(".") + 7);


        try {
            //构造客户端
            CloseableHttpClient client = HttpClients.createDefault();
            //构造请求
            HttpGet get = new HttpGet();
            URI uri = new URI(properties.getGetDistanceUrl() + "origin=" + orLat + "," + orLng + "&destination=" + reLat + "," + reLng + "&ak=" + properties.getAk());
            get.setURI(uri);
            //发送请求
            CloseableHttpResponse response = client.execute(get);
            //判断是否获取成功
            if (response.getStatusLine().getStatusCode() != 200) throw new RuntimeException("获取骑行路线失败");

            //解析结果
            String entity = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(entity);
            Object status = jsonObject.get("status");
            if (status.equals(2002)){
                throw new RuntimeException("超出距离限制，没有骑行路线");
            }

            JSONObject result = (JSONObject) jsonObject.get("result");
            JSONArray routesArray = (JSONArray) result.get("routes");
            JSONObject routes = (JSONObject)routesArray.get(0);
            Integer distance = (Integer) routes.get("distance");


            client.close();
            response.close();

            return distance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
